import axios, { Canceler } from 'axios'
import { ElMessage } from 'element-plus'
function configAxios() {
	// 取消请求
	const cancelRequest: { [key: string]: Canceler } = {}

	// 自定义处理接口结果
	const customRes: { [key: string]: any } = {}

	axios.create({
		baseURL: '',
		timeout: 1000 * 60,
		headers: {
			'Content-Type': 'application/json;charset=UTF-8',
		},
		transformRequest: [
			(data: any) => {
				// 是否为文件上传
				const status = data && data.get && typeof data?.get === 'function' && data?.get('file')?.name
				return status ? data : JSON.stringify(data)
			},
		],
	})

	axios.interceptors.request.use(
		(config) => {
			console.log(config, 'request-config')
			// config.headers.token = 'token'

			// 保存取消请求函数
			config.cancelToken = new axios.CancelToken((c) => {
				cancelRequest[(config.url as string) + `_${Object.keys(cancelRequest).length}`] = c
			})

			// 保存是否自定义处理请求结果
			if (!!config.headers?.customResponse) {
				customRes[config.url as string] = config.headers?.customResponse
				delete config.headers.customResponse
			}
			console.log(cancelRequest, 'cancelRequest')
			return config
		},
		(err) => {
			console.log(err, 'request-err')
		}
	)

	axios.interceptors.response.use(
		(res) => {
			console.log(res, 'response-res')
			const { status, data, config } = res
			// 自定义响应 一般处理单独的接口 例如下载文件流等没有返回code的接口
			if (!!customRes[config.url as string]) {
				delete customRes[config.url as string]
				return Promise.resolve(res)
			}
			let isSuccess = false
			if (status === 200) {
				const code = data.code === undefined ? res.status : data.code
				if (['0', '200', 0, 200].includes(String(code))) {
					isSuccess = true
				}
			}
			// console.log(isSuccess, 'isSuccess')
			if (isSuccess) {
				return Promise.resolve(res.data)
			} else {
				// 错误 这里根据业务code做判断
				ElMessage({
					type: 'error',
					message: data?.msg || data?.message || '请求失败',
					duration: 3000,
				})
				return Promise.reject()
			}
		},
		(err) => {
			const { code, message, config, response } = err
			let errMsg = ''
			// 调用取消请求的错误不做处理
			if (code === 'ERR_CANCELED') {
				return Promise.reject(err)
			}

			switch (code) {
				case 'ERR_NETWORK': // 没网络
					errMsg = '网络错误'
					break
				default:
					errMsg = code || '请求失败'
					break
			}
			if (config.url.includes('/service-dome/api/upload_file')) {
				// errMsg = response.data.detail
				ElMessage({
					type: 'error',
					message: response.data.detail,
					duration: 5000,
				})
				return Promise.reject(err)
			}

			console.log(err, '-res-err', errMsg)
			return Promise.reject(err)
		}
	)

	// 取消请求
	function cancel(url: string = ''): void {
		if (Object.keys(cancelRequest).length) {
			for (const key in cancelRequest) {
				const c = cancelRequest[key]
				if (key.startsWith(url) || !url) {
					c()
					delete cancelRequest[key]
				}
			}
		}
	}

	return {
		send: axios,
		cancel,
	}
}

export const { send, cancel } = configAxios()
